package com.tgz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.tgz.alisms.SmsUtil;
import com.tgz.config.MyVar;
import com.tgz.constant.Phone;
import com.tgz.model.Bscreen;
import com.tgz.mapper.BscreenMapper;
import com.tgz.service.IBscreenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tgz.util.RandomString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 * 弹幕 服务实现类
 * </p>
 *
 * @author hsj
 * @since 2022-12-22
 */
@Service
public class BscreenServiceImpl extends ServiceImpl<BscreenMapper, Bscreen> implements IBscreenService {

//    @Autowired
//    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    public SimpMessagingTemplate template;
    @Autowired
    private MyVar myVar;

    @Override
    public List<Bscreen> findAllBscree() {
        return baseMapper.findAllBscree();
    }

    @Override
    public List<Bscreen> findAllBscreeWithNoCheckStatus() {
        return baseMapper.findAllBscreeWithNoCheckStatus();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized Integer addMsg(String msg) throws Exception {
        if (StringUtils.isEmpty(msg)){
            throw new Exception("很抱歉，您输入的弹幕不能为空！");
        }
        //去除空格
        msg = msg.trim();
        Bscreen bscreenEntity = new Bscreen();
        bscreenEntity.setId(IdWorker.getId());
        bscreenEntity.setMsg(msg);
        Integer count = baseMapper.insert(bscreenEntity);
        //异步发送websocket【需要审核】
        if(count != null && count > 0){
//            String phoneConstant = msg;
//            CompletableFuture.runAsync(()->{
                //发送广播消息
                bscreenEntity.setIsDeleted(Phone.IS_DELETED_0);
                bscreenEntity.setStatus(Phone.STATUS_0);
                bscreenEntity.setIdStr(bscreenEntity.getId().toString());
                template.convertAndSend(myVar.getTopicChannel(), bscreenEntity);
//            },threadPoolTaskExecutor);
        }
        return count;
    }
}
